export function downloadExcel(res, name) {
  //   const fileName = res.headers['content-disposition'].split('=')[1];
  const fileName = name;
  const blobData = res;
  const mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  download(blobData, fileName, mime);
}

export function downloadWord(res, name) {
  const fileName = name;
  const blobData = res;
  const mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  download(blobData, fileName, mime);
}

export function downloadForm(url, params) {
  const form = document.createElement('form');
  form.id = 'form';
  form.name = 'form';
  form.target = '_blank';
  form.enctype = 'application/x-www-form-urlencoded';
  document.body.appendChild(form);
  for (const obj in params) {
    if (params.hasOwnProperty(obj)) {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = obj;
      input.value = params[obj];
      form.appendChild(input);
    }
  }
  form.method = 'POST';
  form.action = url;
  form.submit();
  document.body.removeChild(form);
}

function download(data, filename, mime) {
  const blobData = [data];
  const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
  const exportFileName = filename ? decodeURIComponent(filename) : filename;
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(blob, exportFileName);
  } else {
    const blobURL = window.URL.createObjectURL(blob);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', exportFileName);
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(blobURL);
  }
}
